package com.agranee.timemanagementsystem.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class Utility {
	private static Logger log = Logger.getLogger(Utility.class.getName());

	public String encryptInMd5(String toEncrypt) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");
			byte[] toEnryptInByte = toEncrypt.getBytes();
			messageDigest.reset();
			byte[] digested = messageDigest.digest(toEnryptInByte);
			StringBuffer stringBuffer = new StringBuffer();
			for (int index = 0; index < digested.length; index++) {
				stringBuffer
						.append(Integer.toHexString(0xff & digested[index]));

			}
			return stringBuffer.toString();

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			log.error("Error in MD5 method at : " + new Date() + " is : " + e);
			return null;
		}
	}

	public static void sendMail(final String userName, final String password,
			String from,String to, String subject, String content) {
		

		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(userName,password);
				}
			});
 
		try {
 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");
 
			Transport.send(message);
 
			System.out.println("Done");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}

}
